package com.wmh.baseservice.skd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.wmh.baseservice.common.address.parse.AddressParse;
import com.wmh.baseservice.common.address.parse.ParseResult;
import com.wmh.baseservice.common.service.TokenService;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.skd.pojo.dto.UserAddressDTO;
import com.wmh.baseservice.user.pojo.UsAddress;
import com.wmh.baseservice.user.service.UsAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Api(tags = "用户收获地址信息接口")
@Validated
@RestController
@RequestMapping(value = "user-addresses", produces = "text/plain;charset=utf-8")
@Slf4j
public class UserAddressController {
    @Resource
    private TokenService tokenService;
    @Resource
    private UsAddressService usAddressService;

    /**
     * #0031 智能解析地址
     * @param text 收货地址信息
     * @return 返回解析后的地址信息
     */
    @ApiOperation("智能解析地址")
    @GetMapping("parse")
    public String addressParse(@NotNull(message = "未提交地址信息") String text) {
        List<ParseResult> parseList = AddressParse.parse(text);
        UserAddressDTO userAddressDTO = new UserAddressDTO();
        userAddressDTO
                .setName(parseList.get(0).getName())
                .setPhone(parseList.get(0).getMobile())
                .setProvince(parseList.get(0).getProvince())
                .setCity(parseList.get(0).getCity())
                .setArea(parseList.get(0).getArea())
                .setAddress(parseList.get(0).getDetail());
        return ReturnBody.success(userAddressDTO);
    }

    /**
     * #0032 添加用户地址
     * @return 返回是否添加成功信息
     */
    @ApiOperation("添加用户地址")
    @PostMapping
    public String add(@Valid UserAddressDTO userAddressDTO) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        UsAddress usAddress = new UsAddress();
        usAddress.setUsId(usId)
                .setName(userAddressDTO.getName())
                .setPhone(userAddressDTO.getPhone())
                .setProvince(userAddressDTO.getProvince())
                .setCity(userAddressDTO.getCity())
                .setArea(userAddressDTO.getArea())
                .setAddress(userAddressDTO.getAddress());
        usAddressService.save(usAddress);
        return ReturnBody.success("添加成功!");
    }

    /**
     * #0033 删除用户地址
     * @return 返回是否删除成功信息
     */
    @ApiOperation("删除用户地址")
    @DeleteMapping
    public String delete(@NotNull(message = "未提交用户地址id") Long addressId) {
        UsAddress res = usAddressService.getById(addressId);
        if (Objects.isNull(res)) {
            return ReturnBody.error("该用户地址不存在!");
        } else {
            usAddressService.removeById(addressId);
            return ReturnBody.success("删除成功!");
        }
    }

    /**
     * #0034 修改用户地址列表
     * @return 返回是否修改成功信息
     */
    @ApiOperation("修改用户地址列表")
    @PutMapping
    public String modify(@Valid UserAddressDTO userAddressDTO) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        if (Objects.isNull(userAddressDTO.getId())) {
            return ReturnBody.error("请提交修改地址id!");
        } else {
            UsAddress usAddress = usAddressService.getById(userAddressDTO.getId());
            if (Objects.isNull(usAddress)){
                return ReturnBody.error("该用户地址不存在!");
            }
            usAddress.setId(userAddressDTO.getId())
                    .setUsId(usId)
                    .setName(userAddressDTO.getName())
                    .setPhone(userAddressDTO.getPhone())
                    .setProvince(userAddressDTO.getProvince())
                    .setCity(userAddressDTO.getCity())
                    .setArea(userAddressDTO.getArea())
                    .setAddress(userAddressDTO.getAddress())
                            .setUpdateTime(null);
            usAddressService.saveOrUpdate(usAddress);
            return ReturnBody.success("修改成功!");
        }
    }

    /**
     * #0035 查询用户地址列表
     * @return 返回用户地址列表
     */
    @ApiOperation("查询用户地址列表")
    @GetMapping
    public String queryListByUsId() {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        // 查询用户地址列表
        List<UsAddress> usAddresses = usAddressService.list(new QueryWrapper<UsAddress>().eq("us_id", usId));

        // 将实体列表转换为DTO列表
        List<UserAddressDTO> res = usAddresses.stream().map(address -> new UserAddressDTO()
                .setId(address.getId())
                .setProvince(address.getProvince())
                .setCity(address.getCity())
                .setArea(address.getArea())
                .setAddress(address.getAddress())
                .setName(address.getName())
                .setPhone(address.getPhone())
        ).collect(Collectors.toList());

        return ReturnBody.success(res);
    }
}
